package au.edu.adelaide.mips_soft_core.board_interface_pc.ui;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class Preferences {
	
	private static ArrayList<Pair> pList = new ArrayList<Pair>();
	static {
		try{
			readFromFile();
		}catch(Exception ex){
			System.err.println("Preferences not supported");
		}
	}
	
	public static void setValue(String key, String value){
		Pair p = findPair(key);
		if(p == null){
			p = new Pair();
			p.key = key;
			pList.add(p);
		}
		p.value = value;
		writeToFile();
	}
	
	static void writeToFile(){
		File f = new File("preferences.txt");
		try{
			BufferedWriter out = new BufferedWriter (new OutputStreamWriter( new FileOutputStream(f)));
			for(int i = 0; i < pList.size(); i++){
				Pair p = pList.get(i);
				out.write(p.key + ":" + p.value);
				out.newLine();
			}
			out.flush();
			out.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}
	
	
	static void readFromFile(){
		File f = new File("preferences.txt");
		if(!f.exists()){
			return;
		}
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
			String line = reader.readLine();
			while(line != null){
				if(!line.equals("")){
					int index = line.indexOf(":");
					if(index != -1){
						Pair p = new Pair();
						p.key = line.substring(0, index);
						p.value = line.substring(index + 1);
						pList.add(p);
					}
				}
				line = reader.readLine();
			}
			reader.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public static void setValueStringArray(String key, String[] values, String delim){
		String value = "";
		for(int i = 0; i < values.length; i++){
			if(i != 0){
				value = value + delim;
			}
			value = value + values[i];
		}
		setValue(key, value);
	}
	
	public static String[] getValueStringArray(String key, String delim){
		String val = getValue(key);
		if(val != null){
			return val.split(delim);
		}
		return null;
	}
	
	public static String getValue(String key){
		Pair p = findPair(key);
		if(p != null){
			return p.value;
		}
		return null;
	}
	
	static Pair findPair(String key){
		for(int i = 0; i < pList.size(); i++){
			Pair p = pList.get(i);
			if(p.key.equals(key)){
				return p;
			}
		}
		return null;
	}
	
	static class Pair{
		String key;
		String value;
		
	}

}
